﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using Global;
using Common;
using System.Diagnostics;
using System.Xml;
using System.Runtime.InteropServices;
using OpenNETCF.Desktop.Communication;




namespace FileSync
{
    public partial class FrmMain : Form
    {
        public  ArrayList fileAL=new ArrayList();

        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnLibrary_Click(object sender, EventArgs e)
        {
            folderBD.SelectedPath = txtLibrary.Text;
            DialogResult dr = folderBD.ShowDialog();
            //MessageBox.Show(dr.ToString());
            if (dr == DialogResult.OK)
            {
                txtLibrary.Text = folderBD.SelectedPath;
            }
            
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            txtLibrary.Text = VariableDefine.LibraryPath;
            txtExt.Text = VariableDefine.ExtendName;
            txtTarget.Text = VariableDefine.TargetPath;
            chkMove.Checked = VariableDefine.isMove;
            chkFolder.Checked = VariableDefine.isFolder;
            chkSubFolders.Checked = VariableDefine.isSubFolders;

            
            
            lvMain.ListViewItemSorter = new Common.ListViewColumnSorter();
            lvMain.ColumnClick += new ColumnClickEventHandler(Common.ListViewHelper.ListView_ColumnClick);
            Load2Treeview();

        }

        private void Load2Treeview()
        {
            this.stLabDoing.Visible = false;
            this.stLabPrg.Visible = true;
            stLabPrg.Style = ProgressBarStyle.Continuous;
            fileAL.Clear();
            lvMain.Items.Clear();
            int longestName = 4,longestSize=9;
            stLabPrg.Visible = true;
            string libLoaction = txtLibrary.Text;
            getAllFiles(libLoaction,txtExt.Text.Trim(),chkSubFolders.Checked);
            stLabPrg.Minimum = 0;
            stLabPrg.Value = 0;
            stLabPrg.Maximum = fileAL.Count;
            foreach( FileInfo flInfo in fileAL) 
            {
                if ((flInfo.Name.Length > longestName) & (flInfo.Name.Length<20))
                    longestName = flInfo.Name.Length;
                int tempsize=(int)flInfo.Length / 1024;
                if ((tempsize.ToString().Length > longestSize) & (tempsize.ToString().Length<10))
                    longestSize = tempsize.ToString().Length;
                ListViewItem lvi = new ListViewItem();
                lvi.SubItems[0].Text = flInfo.Name;
                lvi.SubItems.Add(tempsize.ToString());
                lvi.SubItems.Add(flInfo.LastWriteTime.ToString());
                lvi.SubItems.Add(flInfo.DirectoryName);
                lvMain.Items.Add(lvi);
                stLabPrg.Value++;
            }
            lvMain.Columns[0].Width = longestName * 8;
            lvMain.Columns[1].Width = longestSize * 8;
            lvMain.Columns[3].Width = lvMain.Width - 160 - lvMain.Columns[0].Width - lvMain.Columns[1].Width;
            stLabPrg.Visible = false;
            stLabDoing.Visible = true;
            stLabDoing.Text = lvMain.Items.Count.ToString() + @" "+txtExt.Text.ToUpper()+@" file(s).";            
        }

        private void getAllFiles(string path,string extName,Boolean isSub)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            DirectoryInfo[] dirS = dirInfo.GetDirectories();
            FileInfo[] fl = dirInfo.GetFiles();
            foreach (FileInfo fii in fl)
            {
                if (extName == "")
                {
                    fileAL.Add(fii);
                }
                else
                {
                    if (fii.Extension.ToLower() == @"."+extName.ToLower())
                        fileAL.Add(fii);
                }
            }
            if (isSub)
            {
                foreach (DirectoryInfo di in dirS)
                {
                    getAllFiles(di.FullName, extName, isSub);
                }
            }
        }

        private void btnScan_Click(object sender, EventArgs e)
        {
            Load2Treeview();

            //save settings to ini
            VariableDefine.LibraryPath = txtLibrary.Text;
            VariableDefine.ExtendName = txtExt.Text;
            VariableDefine.TargetPath = txtTarget.Text;
            VariableDefine.isMove = chkMove.Checked;
            VariableDefine.isFolder = chkFolder.Checked;
            VariableDefine.isSubFolders = chkFolder.Checked;
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(Application.StartupPath + @"\config.ini");
            foreach (XmlNode xn in xdoc.ChildNodes[1].ChildNodes)
            {
                if (xn.Name == "LibraryPath")
                {

                    xn.InnerText = VariableDefine.LibraryPath;

                }
                if (xn.Name == "ExtendName")
                {

                    xn.InnerText = VariableDefine.ExtendName;
                }
                if (xn.Name == "TargetPath")
                {
                    xn.InnerText = VariableDefine.TargetPath;
                }
                if (xn.Name == "isMove")
                {
                    xn.InnerText = VariableDefine.isMove.ToString();
                }
                if (xn.Name == "isFolder")
                {
                    xn.InnerText = VariableDefine.isFolder.ToString();
                }
                if (xn.Name == "isSubFolders")
                {
                    xn.InnerText = VariableDefine.isSubFolders.ToString();
                }

            }
            xdoc.Save(Application.StartupPath + @"\config.ini");
            xdoc = null;
        }


        private void lvMain_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            Boolean isAllCheck = true;
            foreach (ListViewItem lv in lvMain.Items)
            {
                if (lv.Checked == false)
                    isAllCheck = false;
            }
            chkAll.Checked = isAllCheck;
            float fCheckedSize=0;
            foreach (ListViewItem lv in lvMain.CheckedItems)
            {
                fCheckedSize = fCheckedSize + long.Parse(lv.SubItems[1].Text.ToString());
            }
            string strTotalSize="";
            if ((fCheckedSize / 1024) < 1024)
            {
                strTotalSize = " Size is " + (fCheckedSize / 1024).ToString("F2") + "(MB).";
            }
            else
            {
                strTotalSize = " Size is " + ((fCheckedSize / 1024)/1024).ToString("F2") + "(GB).";
            }

            stLabDoing.Text = @"Checked " + lvMain.CheckedItems.Count.ToString() +@"/" + lvMain.Items.Count.ToString() + @" file(s)."+strTotalSize;
        }

        private void chkAll_Click(object sender, EventArgs e)
        {
            
            if (chkAll.Checked)
            {
                foreach (ListViewItem lv in lvMain.Items)
                {
                    lv.Checked = true;
                }
            }
            else
            {
                foreach (ListViewItem lv in lvMain.Items)
                {
                    lv.Checked = false;
                }
            }
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            if (txtLibrary.Text == txtTarget.Text)
            {
                MessageBox.Show(@"Donot use the same directory!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            stLabDoing.Visible = false;
            stLabPrg.Visible = true;
            stLabPrg.Value = 0;
            stLabPrg.Minimum = 0;
            stLabPrg.Maximum = lvMain.CheckedItems.Count;
            foreach (Control ct in this.Controls)
            {
                ct.Enabled = false;
            }
            try
            {
                
                foreach (ListViewItem lvi in lvMain.CheckedItems)
                {
                    if (!chkFolder.Checked)
                    {
                        FileInfo fl = new FileInfo(lvi.SubItems[3].Text + @"\" + lvi.SubItems[0].Text);
                        if (!chkMove.Checked)
                        {
                            fl.CopyTo(txtTarget.Text.Trim() + @"\" + lvi.SubItems[0].Text, true);
                        }
                        else
                        {
                            fl.MoveTo(txtTarget.Text.Trim() + @"\" + lvi.SubItems[0].Text);
                        }
                        fl = null;
                        stLabPrg.Value++;
                    }
                    else
                    {
                        //create directory
                        string oriDir = lvi.SubItems[3].Text.ToString();
                        string chgDir = oriDir.Replace(txtLibrary.Text + @"\", @"");
                        string[] splitDir = chgDir.Split('\\');
                        string baseDir = txtTarget.Text;
                        for (int i = 0; i < splitDir.Length; i++)
                        {
                            baseDir = baseDir + @"\" + splitDir[i];
                            if (!Directory.Exists(baseDir))
                            {
                                Directory.CreateDirectory(baseDir);
                            }
                        }
                        //copy or move file
                        FileInfo fl = new FileInfo(lvi.SubItems[3].Text + @"\" + lvi.SubItems[0].Text);
                        if (!chkMove.Checked)
                        {
                            fl.CopyTo(baseDir + @"\" + lvi.SubItems[0].Text, true);
                        }
                        else
                        {
                            if (File.Exists(baseDir + @"\" + lvi.SubItems[0].Text))
                            {
                                File.Delete(baseDir + @"\" + lvi.SubItems[0].Text);
                            }
                            fl.MoveTo(baseDir + @"\" + lvi.SubItems[0].Text);
                        }
                        fl = null;
                        stLabPrg.Value++;
                    }
                }
                stLabPrg.Visible = false;
                stLabDoing.Visible = true;
                if (!chkMove.Checked)
                {
                    stLabDoing.Text = lvMain.CheckedItems.Count.ToString() + " are copied.";
                }
                else
                {
                    stLabDoing.Text = lvMain.CheckedItems.Count.ToString() + " are movied.";
                }
            }
            catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                    stLabPrg.Visible = false;
                    stLabDoing.Visible = true;
                    stLabDoing.Text = ex.Message;
                    
                }

            foreach (Control ct in this.Controls)
            {
                ct.Enabled = true;
            }



            // Load2Treeview();
        }

        private void btnTarget_Click(object sender, EventArgs e)
        {
            folderBD.SelectedPath = txtTarget.Text;
            DialogResult dr = folderBD.ShowDialog();
            //MessageBox.Show(dr.ToString());
            if (dr == DialogResult.OK)
            {
                txtTarget.Text = folderBD.SelectedPath;
            }
        }

        private void lvMain_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                cmLvMain.Show(MousePosition.X, MousePosition.Y);
        }

        private void mmOpen_Click(object sender, EventArgs e)
        {

            foreach (ListViewItem lvi in lvMain.SelectedItems)
            {
                System.Diagnostics.Process.Start(lvi.SubItems[3].Text + @"\" + lvi.SubItems[0].Text);
            }
            
            //MessageBox.Show(lvi.SubItems[0].ToString());
            
        }


        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void btn2Mobile_Click(object sender, EventArgs e)
        {

            RAPI wmRAPI = new RAPI();
            if (!wmRAPI.DevicePresent)
            {
                MessageBox.Show("Please connect your mobile to this computer.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            
        }

        private void lvMain_DoubleClick(object sender, EventArgs e)
        {
            foreach (ListViewItem lvi in lvMain.SelectedItems)
            {
                System.Diagnostics.Process.Start(lvi.SubItems[3].Text + @"\" + lvi.SubItems[0].Text);
            }
        }

        private void FrmMain_Resize(object sender, EventArgs e)
        {
            
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            //this.ScaleControl(1, BoundsSpecified.All);
            //this.lvMain.Scale(1F);
        }







    }
}
